<template>
	<scroll-view 
		class="login-container" 
		scroll-y 
		:scroll-into-view="scrollIntoView"
		:enable-back-to-top="false"
	>
		<!-- 顶部装饰区域 -->
		<view class="top-decoration"></view>
		
		<!-- 主要内容区域 -->
		<view class="main-content" :class="{ 'keyboard-active': keyboardActive }" :style="{ paddingTop: (keyboardActive ? 180 : 100) + (statusBarHeight * 2) + 'rpx' }">
			<!-- Logo和标题区域 -->
			<view class="header-section" :class="{ 'compact': keyboardActive }">
				<view class="logo-wrapper">
					<image class="logo" src="/static/logo.svg" mode="aspectFit"></image>
				</view>
				<view class="title-group">
					<text class="main-title">极简Todo</text>
					<text class="sub-title" v-show="!keyboardActive">高效管理您的每一天</text>
				</view>
			</view>

			<!-- 登录表单区域 -->
			<view class="form-section" id="form-section">
				<!-- 手机号输入 -->
				<view class="input-group">
					<view class="input-wrapper">
						<view class="input-icon phone-icon"></view>
						<input 
							class="form-input" 
							placeholder="请输入手机号" 
							v-model="loginForm.phone" 
							maxlength="11"
							type="number"
							placeholder-class="input-placeholder"
							@focus="handleInputFocus('phone')"
							@blur="handleInputBlur"
						/>
					</view>
				</view>
				
				<!-- 验证码输入 -->
				<view class="input-group">
					<view class="input-wrapper code-wrapper">
						<view class="input-icon code-icon"></view>
						<input 
							class="form-input code-input" 
							placeholder="请输入验证码" 
							v-model="loginForm.code" 
							maxlength="6"
							type="number"
							placeholder-class="input-placeholder"
							@focus="handleInputFocus('code')"
							@blur="handleInputBlur"
						/>
						<button 
							class="code-button" 
							:class="{ 'disabled': codeCountdown > 0 }"
							:disabled="codeCountdown > 0"
							@click="sendCode"
						>
							{{ codeCountdown > 0 ? `${codeCountdown}s` : '获取验证码' }}
						</button>
					</view>
				</view>
				
				<!-- 登录按钮 -->
				<view class="button-group">
					<button 
						class="login-btn" 
						:class="{ 'loading': loginLoading }"
						:disabled="loginLoading"
						@click="handleLogin"
					>
						<text v-if="!loginLoading">立即登录</text>
						<view v-else class="loading-content">
							<view class="loading-spinner"></view>
							<text class="loading-text">登录中...</text>
						</view>
					</button>
				</view>
			</view>

			<!-- 提示信息区域 -->
			<view class="tips-section" v-show="!keyboardActive">
				<view class="tip-item">
					<text class="tip-icon">✨</text>
					<text class="tip-text">首次登录会自动注册账号</text>
				</view>
				<view class="tip-item">
					<text class="tip-icon">⏰</text>
					<text class="tip-text">验证码有效期为5分钟</text>
				</view>
			</view>
		</view>
		
		<!-- 底部装饰 -->
		<view class="bottom-decoration"></view>
		
		<!-- 验证码弹窗 -->
		<CaptchaDialog 
			:visible="showCaptchaDialog" 
			@close="closeCaptchaDialog"
			@success="handleCaptchaSuccess"
		></CaptchaDialog>
	</scroll-view>
</template>

<script>
import { sendSmsCode, login } from '../../api/user'
import CaptchaDialog from '../../components/CaptchaDialog.vue'

export default {
	components: {
		CaptchaDialog
	},
	data() {
		return {
			loginForm: {
				phone: '',
				code: ''
			},
			loginLoading: false,
			codeCountdown: 0,
			keyboardActive: false,
			scrollIntoView: '',
			keyboardHeight: 0,
			statusBarHeight: 0,
			showCaptchaDialog: false,
			smsClickCount: 0, // 记录点击获取验证码的次数
			lastSmsPhone: '' // 记录上次发送验证码的手机号
		}
	},
	
	mounted() {
		// 获取状态栏高度
		uni.getSystemInfo({
			success: (res) => {
				this.statusBarHeight = res.statusBarHeight || 0
			}
		})
		
		// 监听键盘弹出和收起
		if (uni.onKeyboardHeightChange) {
			uni.onKeyboardHeightChange((res) => {
				this.keyboardHeight = res.height
				this.keyboardActive = res.height > 0
				
				// 键盘弹出时，延迟滚动到表单区域
				if (res.height > 0) {
					setTimeout(() => {
						this.scrollIntoView = 'form-section'
					}, 100)
				} else {
					this.scrollIntoView = ''
				}
			})
		}
		
		// 备用方案：监听窗口大小变化
		let initialHeight = 0
		uni.getSystemInfo({
			success: (res) => {
				initialHeight = res.windowHeight
			}
		})
		
		// 定期检查窗口高度变化（备用方案）
		this.heightCheckTimer = setInterval(() => {
			uni.getSystemInfo({
				success: (res) => {
					const heightDiff = initialHeight - res.windowHeight
					if (heightDiff > 150 && !this.keyboardActive) {
						// 键盘可能弹出了
						this.keyboardActive = true
						setTimeout(() => {
							this.scrollIntoView = 'form-section'
						}, 200)
					} else if (heightDiff <= 80 && this.keyboardActive) {
						// 键盘可能收起了
						this.keyboardActive = false
						this.scrollIntoView = ''
					}
				}
			})
		}, 300)
	},
	
	beforeDestroy() {
		// 清理定时器
		if (this.heightCheckTimer) {
			clearInterval(this.heightCheckTimer)
		}
	},
	methods: {
		// 处理输入框获得焦点
		handleInputFocus(type) {
			this.keyboardActive = true
			// 延迟滚动，确保键盘完全弹出
			setTimeout(() => {
				this.scrollIntoView = 'form-section'
			}, 400)
		},
		
		// 处理输入框失去焦点
		handleInputBlur() {
			// 延迟处理，避免在切换输入框时闪烁
			setTimeout(() => {
				// 检查是否还有输入框处于焦点状态
				const activeElement = uni.createSelectorQuery().select(':focus')
				if (!activeElement) {
					this.keyboardActive = false
					this.scrollIntoView = ''
				}
			}, 100)
		},
		
		// 验证手机号格式
		validatePhone(phone) {
			const phoneRegex = /^1[3-9]\d{9}$/
			return phoneRegex.test(phone)
		},
		
		// 验证验证码格式
		validateCode(code) {
			const codeRegex = /^\d{6}$/
			return codeRegex.test(code)
		},
		
		// 发送验证码
		async sendCode() {
			if (!this.loginForm.phone) {
				uni.showToast({ title: '请先输入手机号', icon: 'none' })
				return
			}
			
			if (!this.validatePhone(this.loginForm.phone)) {
				uni.showToast({ title: '手机号格式不正确', icon: 'none' })
				return
			}
			
			// 检查是否是第二次点击同一个手机号
			if (this.lastSmsPhone === this.loginForm.phone && this.smsClickCount >= 1) {
				// 第二次或更多次点击，显示验证码弹窗
				this.showCaptchaDialog = true
				return
			}
			
			// 第一次点击，直接发送验证码
			this.performSendCode()
		},
		
		// 执行发送验证码
		async performSendCode() {
			try {
				uni.showLoading({ title: '发送中...' })
				
				const response = await sendSmsCode(this.loginForm.phone)
				
				if (response.code === 200) {
					uni.showToast({ title: '验证码发送成功', icon: 'success' })
					
					// 记录点击次数和手机号
					if (this.lastSmsPhone === this.loginForm.phone) {
						this.smsClickCount++
					} else {
						this.smsClickCount = 1
						this.lastSmsPhone = this.loginForm.phone
					}
					
					// 开始倒计时
					this.codeCountdown = 60
					const timer = setInterval(() => {
						this.codeCountdown--
						if (this.codeCountdown <= 0) {
							clearInterval(timer)
						}
					}, 1000)
				} else {
					uni.showToast({ title: response.message || '发送验证码失败', icon: 'none' })
				}
			} catch (error) {
				console.error('发送验证码失败:', error)
				uni.showToast({ title: error.message || '发送验证码失败', icon: 'none' })
			} finally {
				uni.hideLoading()
			}
		},
		
		// 登录
		async handleLogin() {
			if (!this.loginForm.phone) {
				uni.showToast({ title: '请输入手机号', icon: 'none' })
				return
			}
			
			if (!this.validatePhone(this.loginForm.phone)) {
				uni.showToast({ title: '手机号格式不正确', icon: 'none' })
				return
			}
			
			if (!this.loginForm.code) {
				uni.showToast({ title: '请输入验证码', icon: 'none' })
				return
			}
			
			if (!this.validateCode(this.loginForm.code)) {
				uni.showToast({ title: '验证码格式不正确', icon: 'none' })
				return
			}
			
			try {
				this.loginLoading = true
				
				const response = await login(this.loginForm)
				
				if (response.code === 200) {
					// 保存登录状态和用户信息
					uni.setStorageSync('isLoggedIn', true)
					uni.setStorageSync('token', response.data.token)
					uni.setStorageSync('userInfo', {
						...response.data.user,
						avatar: '/static/logo.png' // 使用默认头像
					})
					
					uni.showToast({ title: '登录成功', icon: 'success' })
					
					setTimeout(() => {
						uni.reLaunch({ url: '/pages/index/index' })
					}, 800)
				} else {
					uni.showToast({ title: response.message || '登录失败', icon: 'none' })
				}
			} catch (error) {
				console.error('登录失败:', error)
				uni.showToast({ title: error.message || '登录失败', icon: 'none' })
			} finally {
				this.loginLoading = false
			}
		},
		
		// 关闭验证码弹窗
		closeCaptchaDialog() {
			this.showCaptchaDialog = false
		},
		
		// 验证码验证成功
		handleCaptchaSuccess(captchaData) {
			console.log('验证码验证成功:', captchaData)
			// 验证成功后，发送短信验证码
			this.performSendCode()
		},
		
		// 重置验证码相关状态（当手机号改变时）
		resetSmsState() {
			if (this.loginForm.phone !== this.lastSmsPhone) {
				this.smsClickCount = 0
				this.lastSmsPhone = ''
			}
		}
	},
	
	watch: {
		// 监听手机号变化，重置验证码状态
		'loginForm.phone'(newPhone, oldPhone) {
			if (newPhone !== oldPhone) {
				this.resetSmsState()
			}
		}
	}
}
</script>

<style>
/* 页面容器 */
.login-container {
	min-height: 100vh;
	height: 100vh;
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	position: relative;
	overflow: hidden;
	-ms-overflow-style: none;
	scrollbar-width: none;
}

/* 滚动视图样式 */
.login-container::-webkit-scrollbar {
	display: none;
}

/* 顶部装饰 */
.top-decoration {
	position: absolute;
	top: -100rpx;
	right: -100rpx;
	width: 400rpx;
	height: 400rpx;
	background: rgba(255, 255, 255, 0.1);
	border-radius: 50%;
}

/* 底部装饰 */
.bottom-decoration {
	position: absolute;
	bottom: -150rpx;
	left: -150rpx;
	width: 500rpx;
	height: 500rpx;
	background: rgba(255, 255, 255, 0.05);
	border-radius: 50%;
}

/* 主要内容区域 */
.main-content {
	position: relative;
	z-index: 10;
	padding: 0 40rpx 60rpx;
	min-height: 100vh;
	display: flex;
	flex-direction: column;
	justify-content: center;
	transition: all 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94);
}

/* 键盘弹出时的样式调整 */
.main-content.keyboard-active {
	justify-content: flex-start;
	min-height: auto;
}

/* 头部区域 */
.header-section {
	text-align: center;
	margin-bottom: 80rpx;
	transition: all 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94);
}

/* 键盘弹出时的紧凑模式 */
.header-section.compact {
	margin-bottom: 70rpx;
}

.header-section.compact .logo {
	width: 140rpx;
	height: 140rpx;
}

.header-section.compact .main-title {
	font-size: 48rpx;
	margin-bottom: 14rpx;
}

.logo-wrapper {
	margin-bottom: 40rpx;
	transition: all 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94);
}

.header-section.compact .logo-wrapper {
	margin-bottom: 35rpx;
}

.logo {
	width: 160rpx;
	height: 160rpx;
	border-radius: 32rpx;
	box-shadow: 0 16rpx 40rpx rgba(0, 0, 0, 0.15);
	transition: all 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94);
}

.title-group {
	margin-bottom: 20rpx;
}

.main-title {
	display: block;
	font-size: 56rpx;
	font-weight: 700;
	color: #ffffff;
	margin-bottom: 16rpx;
	text-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.2);
	transition: all 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94);
}

.sub-title {
	display: block;
	font-size: 28rpx;
	color: rgba(255, 255, 255, 0.8);
	font-weight: 400;
	transition: opacity 0.3s ease;
}

/* 表单区域 */
.form-section {
	margin-bottom: 60rpx;
}

.input-group {
	margin-bottom: 32rpx;
}

.input-wrapper {
	background: rgba(255, 255, 255, 0.95);
	border-radius: 24rpx;
	padding: 8rpx;
	display: flex;
	align-items: center;
	box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
	backdrop-filter: blur(10rpx);
}

.input-icon {
	width: 80rpx;
	height: 80rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	border-radius: 20rpx;
	background: linear-gradient(135deg, #667eea, #764ba2);
	margin-right: 16rpx;
	position: relative;
}

/* 手机图标 */
.phone-icon::before {
	content: '';
	width: 24rpx;
	height: 40rpx;
	border: 3rpx solid #ffffff;
	border-radius: 6rpx;
	position: relative;
}

.phone-icon::after {
	content: '';
	position: absolute;
	width: 12rpx;
	height: 3rpx;
	background: #ffffff;
	border-radius: 2rpx;
	top: 50%;
	left: 50%;
	transform: translate(-50%, 8rpx);
}

/* 验证码图标 */
.code-icon::before {
	content: '';
	width: 32rpx;
	height: 32rpx;
	border: 3rpx solid #ffffff;
	border-radius: 8rpx;
	position: relative;
}

.code-icon::after {
	content: '';
	position: absolute;
	width: 16rpx;
	height: 16rpx;
	background: #ffffff;
	border-radius: 50%;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%);
}

.form-input {
	flex: 1;
	height: 80rpx;
	font-size: 32rpx;
	color: #333;
	background: transparent;
	border: none;
	outline: none;
}

.input-placeholder {
	color: #999;
	font-size: 28rpx;
}

/* 验证码输入特殊样式 */
.code-wrapper {
	padding-right: 8rpx;
}

.code-input {
	margin-right: 16rpx;
}

.code-button {
	height: 64rpx;
	padding: 0 24rpx;
	background: linear-gradient(135deg, #667eea, #764ba2);
	color: #ffffff;
	border: none;
	border-radius: 16rpx;
	font-size: 24rpx;
	font-weight: 500;
	white-space: nowrap;
	min-width: 160rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.code-button.disabled {
	background: #ccc;
	color: #999;
}

/* 登录按钮 */
.button-group {
	margin-top: 40rpx;
}

.login-btn {
	width: 100%;
	height: 96rpx;
	background: linear-gradient(135deg, #ff6b6b, #ee5a24);
	color: #ffffff;
	border: none;
	border-radius: 24rpx;
	font-size: 36rpx;
	font-weight: 600;
	box-shadow: 0 12rpx 40rpx rgba(255, 107, 107, 0.3);
	display: flex;
	align-items: center;
	justify-content: center;
	transition: all 0.3s ease;
}

.login-btn.loading {
	background: #ccc;
	box-shadow: none;
}

.loading-content {
	display: flex;
	align-items: center;
	justify-content: center;
}

.loading-spinner {
	width: 32rpx;
	height: 32rpx;
	border: 4rpx solid rgba(255, 255, 255, 0.3);
	border-top: 4rpx solid #ffffff;
	border-radius: 50%;
	animation: spin 1s linear infinite;
	margin-right: 16rpx;
}

.loading-text {
	font-size: 32rpx;
	color: #ffffff;
}

@keyframes spin {
	0% { transform: rotate(0deg); }
	100% { transform: rotate(360deg); }
}

/* 提示信息区域 */
.tips-section {
	margin-top: 40rpx;
}

.tip-item {
	display: flex;
	align-items: center;
	margin-bottom: 20rpx;
	padding: 0 20rpx;
}

.tip-icon {
	font-size: 28rpx;
	margin-right: 16rpx;
}

.tip-text {
	font-size: 26rpx;
	color: rgba(255, 255, 255, 0.8);
	line-height: 1.4;
}

/* 响应式适配 */
@media screen and (max-width: 750rpx) {
	.main-content {
		padding: 80rpx 30rpx 40rpx;
	}
	
	.main-title {
		font-size: 48rpx;
	}
	
	.form-input {
		font-size: 30rpx;
	}
	
	.login-btn {
		height: 88rpx;
		font-size: 32rpx;
	}
}

/* 小屏幕适配 */
@media screen and (max-height: 1334rpx) {
	.header-section {
		margin-bottom: 60rpx;
	}
	
	.logo {
		width: 120rpx;
		height: 120rpx;
	}
	
	.main-title {
		font-size: 44rpx;
	}
}
</style> 